import time
import json
import os
from random import choice


def generate_person():  # генерация однй персоны
    name = ''
    tel = ''

    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', ]
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

    while len(name) != 5:
        name = name + choice(letters)

    while len(tel) != 7:
        tel = tel + str(choice(nums))

    return {"name": name, "tel": tel}


def time_watcher():  # время выполнения скрипта
    print('--- %s seconds ---' % (time.time() - start_time))


def get_persons():  # получение массива персон
    persons = []
    for i in range(9):
        persons.append(generate_person())
    return persons


def create_json(persons):  # создание json по готовым данным
    path_f = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(path_f, "create_persons.json"), 'w', encoding='utf-8') as json_file:
        json.dump(persons, json_file, indent=2, ensure_ascii=False)


def write_json(person_dict):  # последовательная запись в json
    path_f = os.path.dirname(os.path.abspath(__file__))
    try:
        data = json.load(
            open(os.path.join(path_f, "write_persons.json")))
    except:
        data = []

    data.append(person_dict)

    with open(os.path.join(path_f, "write_persons.json"), 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, indent=2, ensure_ascii=False)


def main():
    # создание готового create_persons.json
    # create_json(get_persons())

    for i in range(9):  # включительно до 8, 9 раз не входит в итерацию
        # последовательная запись в write_persons.json
        write_json(generate_person())


if __name__ == '__main__':
    start_time = time.time()
    main()
    time_watcher()
